
<template>
	<view>
		<view ref="roomTop">
			<view class="video_container" :style="{width:screenWidth+'px',height:(screenWidth / 16 * 9 / 0.8)+'px'}">
				<view class="video_mask" v-if="live_status === 0">
					<u-loadmore status="loading" icon-color="#ffffff" color="#ffffff" />
				</view>
				<view v-if="live_status === 1" id="id_test_video"></view>
				<view v-if="live_status === 2" class="video_mask" :style="`background-image: url(`+roomDetail.cover_pic+`);background-repeat: no-repeat;background-size: cover;`">
					<view style="color:#ffffff;background-color: rgba(0,0,0,.6);padding: 10rpx 30rpx;border-radius: 10rpx;">直播还未开始，请稍后再来~</view>
				</view>
			</view>
			<u-tabs :list="tabList" :is-scroll="false" :current="currentTab" @change="tabChangeHandler"></u-tabs>
		</view>
		
		<!-- 互动 -->
		<view v-if="currentTab === 0">
			<view style="position: relative;">
				<scroll-view scroll-y="true" class="chat-record" 
					:scroll-top="scrollTop" @scroll="recordScroll" 
					:style="{height:(screenHeight-roomTopHeight-roomBottomHeight)+'px'}">
					<!-- :scroll-with-animation="true" -->
					<view ref="recordContent">
						<view style="color:rgba(0,0,0,0.6);font-size: 9pt;padding: 20rpx;">系统提示：兰亭臻选直播内容及互动评论须严格遵守直播规范，严禁传播违法违规、低俗血暴、吸烟酗酒、造谣诈骗等不良有害信息。如有违规，平台将进行封禁直至永久封停账号哦！请勿轻信任何广告信息，谨防上当受骗。</view>
						
						<view v-for="record in recordList" class="record-item">
							<view class="item-left">
								<image v-if="record.avatar_url" class="acatar" :src="record.avatar_url" mode="aspectFill"></image>
								<image v-else class="acatar" src="/static/icon/default-avatar.png" mode="aspectFill"></image>
							</view>
							<view class="item-right">
								<view class="info">
									<view style="display: flex;align-items: center;">
										<u-tag v-for="itm in record.tags" class="tags" type="info" size="mini" :text="itm" mode="dark" />
										
										<u-tag class="tags" type="primary" size="mini" :text="record.role_type" mode="dark" />
										<text v-line-clamp="1" style="font-size: 10pt;">{{record.nickname}}</text>
									</view>
									<view class="time">{{formatTimeToStr(record.time)}}</view>
								</view>
								<view class="content">{{record.content}}</view>
							</view>
						</view>
					</view>
				</scroll-view>
				
				
				<view v-if="ws_connect_status !== 1" class="chat-record-mask" :style="{height:(screenHeight-roomTopHeight-roomBottomHeight)+'px'}">
					<u-loadmore 
						:status=" ws_connect_status === 0 ? 'loading' : 'loadmore'" 
						:load-text="{loading:'服务器连接中...',loadmore:'服务器连接失败！点击重试'}"
						icon-color="#ffffff" color="#ffffff" 
						@loadmore="reconnectSocket()"/>
				</view>
			</view>
			
			<com-chat-input ref="comChatInput" @onConfirm="inputConfirmHandler"></com-chat-input>
		</view>
		
		
		<!-- 介绍 -->
		<view v-if="currentTab === 1">
			<scroll-view scroll-y="true" class="chat-record" :style="{height:(screenHeight-roomTopHeight)+'px'}">
				<view style="padding: 20rpx;">
					<view v-line-clamp="2" style="font-size: 14pt;font-weight: 600;">{{roomDetail.title}}</view>
					<view style="display: flex;margin-top: 20rpx;">
						<view style="width: 100rpx;height: 100rpx;">
							<image v-if="roomDetail.avatar_url" class="acatar" :src="roomDetail.avatar_url" mode="aspectFill"></image>
							<image v-else class="acatar" src="/static/icon/default-avatar.png" mode="aspectFill"></image>
						</view>
						<view style="margin-left: 20rpx;">
							<view>{{roomDetail.nickname}}</view>
							<view>
								<u-tag style="margin-right: 10rpx;" type="info" size="mini" text="主播" mode="dark" />
								<u-tag style="margin-right: 10rpx;" type="primary" size="mini" :text="roomDetail.role_type" mode="dark" />
							</view>
						</view>
					</view>
					<view style="margin-top: 20rpx;">
						<u-parse :html="roomDetail.desc"></u-parse>
					</view>
				</view>
			</scroll-view>
		</view>
		
	</view>

</template>

<script>
	import {formatTimeToStr} from "@/utils/date";
	import socketIo from 'socket.io-client';
	let that;
	export default{
		data(){
			return {
				roomKey:'',//直播间key
				
				screenWidth:0,
				screenHeight:0,
				roomTopHeight:0,
				roomBottomHeight:0,
				
				//直播视频相关
				live_status: 0,//0-待加载，1-直播中，2-未直播
				player:'',
				
				//tab
				tabList:[
					{name:'互动'},
					{name:'介绍'}
				],
				currentTab:0,
				
				//聊天室相关
				socket:'',
				ws_connect_status: 0,//0-待连接，1-已连接，2-已断开
				healthInterval:false,
				recordList:[],
				scrollTop:0,
				oldScrollTop:-1,
				
				
				roomDetail:{
					title:''
				}
				
			}
		},
		beforeCreate(){
			that = this;
		},
		async onLoad(opt){

			let systemInfo = uni.getSystemInfoSync();
			this.screenWidth = systemInfo.screenWidth;
			this.screenHeight = systemInfo.screenHeight;
			
			
			this.roomKey = opt.key ?? '';
			uni.showLoading({title:'正在加载中...',mask:true});
			if(this.roomKey){

				let res = await this.$http.request({
					url: this.$api.live.getRoomByStream,
					method: 'get',
					data:{stream:this.roomKey}
				});
				if(res.code === 0){
					this.roomDetail = res.data;
					this.live_status = res.data.status == 1 ? 1 : 2;
					
					//更新分享内容
					this.$wechatSdk.initShareUrl({
						app_share_desc: this.roomDetail.title,
						app_share_pic: this.roomDetail.cover_pic,
						app_share_title: this.roomDetail.title
					}, window.location.protocol + '//' + window.location.host + window.location.pathname + '#/plugins/live/room?key='+this.roomKey);
					
					
					//初始化长链接聊天室
					this.initSocket();
					
					this.$nextTick(function(){
						that.roomTopHeight = Math.ceil(that.$refs.roomTop.$el.clientHeight);
						that.roomBottomHeight = Math.ceil(that.$refs.comChatInput.$el.clientHeight);	
					})
					
					if(this.live_status == 1){
						this.initVideoPlay();
					}
					uni.hideLoading();
					return ;
				}
			}
			
			
			uni.hideLoading();
			return uni.showModal({
				title:'温馨提示',
				content:'直播间不存在,请稍后重试！',
				showCancel:false,
				success(res){
					if(res.confirm){
						uni.navigateTo({url:'/plugins/live/index'});
					}
				}
			})

			
		},
		//页面卸载时，关闭长链接和定时心跳检测，关闭直播播放
		onUnload(){
			that.ws_connect_status = 0;
			that.socket.close();
			that.clearIntervalHandler();
			//todo 直播视频播放回收
		},
		
		methods:{
			
			//初始化聊天室
			initSocket(){
				
				that.socket = socketIo(that.$api.wss, {
					transports: ["websocket"] ,
					autoConnect: true,
					reconnection: false
				});
				that.socket.on('event', data => {
					that.onSocketEvent(data)
				});
				that.socket.on('disconnect', data =>{
					console.log('disconnect',data);
					that.onSocketClose(data)
				});
				that.socket.on('connect_error',data => {
					console.log('connect_error',data);
					that.onSocketClose(data)
				});
				that.socket.on('message',data =>{
					that.onSocketMessage(data);
				});
				
				that.socket.on('join-room',data=>{
					if(data.status !== 1){
						that.$http.toast(data.msg);
						return ;
					}
					that.ws_connect_status = 1;
					that.createIntervalHandler();
				});
				
				that.socket.on('connect', data => {
					let content = {
						time: that.getTimestamp(),
						room: that.roomKey,
						user_id:0,
						token:''
					};
					let token = uni.getStorageSync('token');
					if(token){
						let userInfo = uni.getStorageSync('userInfo');
						if(userInfo){
							userInfo = JSON.parse(userInfo);
							content.token = token;
							content.user_id = userInfo.user_id;
						}
					}
					that.socket.emit('join-room',content);
				});
			},
			
			//收到socket消息的处理
			onSocketMessage(data){
				//滚动视图高度
				let viewHeight = that.screenHeight - that.roomTopHeight - that.roomBottomHeight;
				//消息渲染前的滚动内容总高度
				let oldContentHeight = that.$refs.recordContent.$el.clientHeight;
				//需要滚动时，滚动到底部数值
				let scrollTop = Math.ceil(oldContentHeight - viewHeight);
				
				
				//定义变量，判断当前情况是否需要滚动到底部
				let is_scroll = false;
				//偏移值 = -1，内容未滚动过，并且高度不足以渲染下一条消息，赋值，消息渲染后，触发自动滚动
				//如果偏移值和滚动到底部的偏差较小，说明目前在底部，赋值，消息渲染后，触发自动滚动
				//其他情况说明用户往上拖动了，则不赋值，不触发自动滚动
				if(that.oldScrollTop === -1 && scrollTop > -100){
					is_scroll = true;
				}else if( Math.abs(that.oldScrollTop - scrollTop) <= 5){
					is_scroll = true;
				}
				
				//将消息push进数组，进行渲染
				that.recordList.push(data);
				//用于消息过多时，释放内存
				if(that.recordList.length > 100){
					that.recordList.splice(0,that.recordList.length - 100);
				}
				
				//自动滚动
				if(is_scroll){
					that.$nextTick(()=>{
						let newContentHeight = that.$refs.recordContent.$el.clientHeight;
						let top = Math.ceil(newContentHeight - viewHeight);
						that.scrollTop = top;
					})
				}

			},
			
			//滚动视图触发滚动时，保存偏移值
			recordScroll(e){
				that.oldScrollTop = e.detail.scrollTop;
			},
			
			//socket事件消息推送，预留后续功能拓展
			onSocketEvent(data){
				console.log("onSocketEvent",data);
				if(data.type == 'modal'){
					uni.showModal(data);
				}else if(data.type == 'toast'){
					uni.showToast(data);
				}
			},
			
			//聊天室链接断开事件
			onSocketClose(e){
				that.ws_connect_status = 2;//修改链接状态
				that.clearIntervalHandler();//关闭心跳数据定时器
			},
			reconnectSocket(){
				that.ws_connect_status = 0;
				that.socket.connect();
			},
			
			//发送心跳数据，维持聊天室长链接不断开
			health(){
				if(that.ws_connect_status === 1){
					console.log('发送心跳数据包');
					that.socket.emit('health', {type:'health',time:that.getTimestamp()} );
				}else{
					console.log('聊天室未连接');
				}
			},
			
			//创建定时器
			createIntervalHandler(){
				if(!that.healthInterval){
					that.healthInterval = setInterval(function(){
						that.health()
					},30000);
				}
			},
			//清除定时器
			clearIntervalHandler(){
				if(that.healthInterval){
					clearInterval(that.healthInterval);
					that.healthInterval = false;
				}
			},
			//获取10位时间戳
			getTimestamp(){
				return Math.ceil(new Date().getTime() / 1000);
			},

			
			//初始化直播播放组件
			initVideoPlay(){
				that.$nextTick(function(){
					//视频最佳宽高比例为9:16
					let width = that.screenWidth;
					let height = parseInt(width/16*9/0.8);//
					let script = document.createElement("script");
					script.type = "text/javascript";
					script.src = "https://web.sdk.qcloud.com/player/tcplayerlite/release/v2.4.5/TcPlayer-2.4.5.js";
					document.getElementsByTagName("head")[0].appendChild(script);
					script.onload = function () {
						that.player = new TcPlayer('id_test_video', {
							"live" : true,
							// "m3u8":"http://lanting-live.h5-mingyuanriji.cn/live/gzh_test.m3u8",
							// "flv":"http://lanting-live.h5-mingyuanriji.cn/live/gzh_test.flv",
							"webrtc" : "webrtc://live-play.zaituan.com.cn/live/"+that.roomKey, //请替换成实际可用的播放地址
							"autoplay" : true,      //iOS 下 safari 浏览器，以及大部分移动端浏览器是不开放视频自动播放这个能力的
							"poster" : that.roomDetail.cover_pic,
							"width" :  width,//视频的显示宽度，请尽量使用视频分辨率宽度
							"height" : height,//视频的显示高度，请尽量使用视频分辨率高度
							listener : function (msg) {
								console.log(123123,msg);

								if(msg.type == 'load') {
									if( !that.player.playing() ){
										uni.showModal({
											title:'系统提示',
											content:'兰亭臻选直播内容及互动评论须严格遵守直播规范，严禁传播违法违规、低俗血暴、吸烟酗酒、造谣诈骗等不良有害信息。如有违规，平台将进行封禁直至永久封停账号哦！请勿轻信任何广告信息，谨防上当受骗。',
											confirmText:'确认',
											showCancel:false,
											success(res){
												if(res.confirm){
													that.player.play();
												}
											}
										});
									}
									
									// var _div = document.createElement('div');
									// _div.className = 'marker';
									// _div.style="position:absolute;top:0;width:100%;height:100%;color:#ffffff;display:flex;align-items:center;justify-content:center";
									// _div.innerText = '测试';
									// document.querySelector('.vcp-player').appendChild(_div)
								}
							}
						});
					}
				});
			},
			
			tabChangeHandler(index){
				this.currentTab = index;
			},
			
			
			//用户发送消息
			inputConfirmHandler(content){
				if(!content) {
					return that.$http.toast('没有需要发送的内容！');
				}
				if(that.ws_connect_status !== 1){
					return that.$http.toast('请先连接服务器！');
				}
				let token = uni.getStorageSync('token');
				if(!token){
					return uni.showModal({
						title:'温馨提示',
						content:'登录后才可在直播间进行发言，是否前往登录？',
						confirmText:'立即前往',
						cancelText:'暂不前往',
						success(e){
							if(e.confirm){
								uni.navigateTo({url:'/pages/public/login'})
							}
						}
					})
				}
				that.socket.emit('message',{
					room: that.roomKey,
					time:that.getTimestamp(),
					content
				})
				//消息发送成功后，清空输入框
				this.$refs.comChatInput.clearInput();
			},
			
		},
		computed:{
			formatTimeToStr(){
				return value => formatTimeToStr(value * 1000,'MM-dd hh:mm')
			}
		},
	
	}
</script>

<style lang="scss">
	@import url('https://web.sdk.qcloud.com/player/tcplayer/release/v4.9.1/tcplayer.min.css');
	
	.video_container {
		background-color: #000;
	}
	.video_mask{
		width: 100%;
		height: 100%;
		display:flex;
		align-items:center;
		justify-content:center;
	}
	
	
	// 聊天室样式
	.chat-record{
		width:100vw;
		background-color: #eeeeee;
	}
	.chat-record-mask{
		width:100vw;
		background-color: rgba(0,0,0,0.8);
		position: absolute;
		top:0;
		left: 0;
		z-index: 9;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.record-item{
		padding: 20rpx;
		display: flex;
		justify-content: start;
	}
	.item-left{
		width: 100rpx;
		height: 100rpx;
		flex: none;
	}
	.item-right{
		width:100%;
		margin-left: 16rpx;
	}
	.acatar {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}
	.record-item .tags{
		margin-right: 5rpx;
		flex:none;
	}
	.item-right>.info{
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.item-right .time{
		flex: none;
		font-size: 9pt;
		margin-left: 20rpx;
	}
	.record-item .content{
		background-color: #fff;
		padding: 25rpx;
		margin-top: 10rpx;
		display: inline-block;
		min-width: 150rpx;
		border-radius: 25rpx;
		font-size: 12pt;
	}
	
	
	
	
	/deep/ ::-webkit-scrollbar {
		 //滚动条整体样式
		    display: block;
		    width: 5px !important;
		    height: 5px !important;
		    -webkit-appearance: auto!important;
		    background: #f2f2f2;
		    overflow: auto!important;
	}
	/deep/ ::-webkit-scrollbar-thumb {
		 //滚动条里面小方块
		   border-radius: 5px !important;
		   box-shadow: inset 0 0 3px rgba(0,0,0,0.2) !important;
		   background-color: #535353 !important;
	}
	/deep/ ::-webkit-scrollbar-track {
		   //滚动条
		   border-radius: 5px !important;
		   box-shadow: inset 0 0 3px rgba(0,0,0,0.2) !important;
		   background-color: #ededed !important;
	}
</style>